package org.gw.ylc.base.util;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.GenericConverter;

import java.util.Collections;
import java.util.Set;

public class FastJSONConverter implements GenericConverter {
	private ConversionService conversionService;

	public FastJSONConverter(ConversionService conversionService) {
		super();
		this.conversionService = conversionService;
	}

	@Override
	public Set<ConvertiblePair> getConvertibleTypes() {
		return Collections.singleton(new ConvertiblePair(JSONObject.class, Object.class));
	}

	@Override
	public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
		JSONObject jsonObject = (JSONObject) source;
		try {
			BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(targetType.getType().newInstance());
			wrapper.setConversionService(conversionService);
			for (String key : jsonObject.keySet()) {
				if (wrapper.isWritableProperty(key))
					wrapper.setPropertyValue(key, jsonObject.get(key));
			}
			return wrapper.getWrappedInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
